package ru.compscicenter.databases.zaikina.common.commands;
import ru.compscicenter.databases.zaikina.common.Logger;

import java.util.Collection;
import java.util.LinkedList;

public class SysCommandBuffer {
    private LinkedList<SysCommand<?, ?>> commands = new LinkedList<SysCommand<?, ?>>();
    private final Logger logger;

    public SysCommandBuffer(Integer nodeId) {
        logger = new Logger(nodeId);
    }

    public void loadCommands() {
        commands.addAll(logger.getNotProcessedCommands());
        logger.normalize();
    }

    public synchronized void add(SysCommand<?, ?> command) {
        logger.addNotProcessedCommands(command);
        commands.add(command);
    }

    public synchronized void addAll(Collection<SysCommand<?, ?>> newCommands) {
        for (SysCommand<?, ?> command : newCommands) {
            logger.addNotProcessedCommands(command);
        }
        commands.addAll(newCommands);
    }

    public synchronized boolean isEmpty() {
        return commands.isEmpty();
    }

    public synchronized void clear() {
        for (SysCommand command : commands) {
            logger.addProcessedCommands(command);
        }
        commands.clear();
    }

    public synchronized LinkedList<SysCommand<?, ?>> value() {
        return commands;
    }
}
